package com.csaba.swing.action;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

import com.csaba.connector.model.Account;
import com.csaba.connector.model.Session;
import com.csaba.swing.MainWindow;
import com.csaba.swing.gui.AccountListView;
import com.csaba.swing.gui.ContextListener;
import com.csaba.swing.gui.GUIContext;
import com.csaba.swing.gui.util.GUIUtil;
import com.csaba.swing.model.AccountCache;

@SuppressWarnings( "serial" )
public class AccountOverviewAction extends AbstractAction implements ContextListener
{
	//private final static Logger logger = Logger.getLogger(AccountOverviewAction.class.getPackage().getName());

	public AccountOverviewAction()
	{
		super(MainWindow.getString("AccountOverviewAction.menuItem")); //$NON-NLS-1$
		setEnabled(false);
		GUIUtil.setMnemonic(this);
		putValue(SMALL_ICON, GUIContext.getIcon("accounts", 16)); //$NON-NLS-1$
		putValue(LARGE_ICON_KEY, GUIContext.getIcon("accounts", 32)); //$NON-NLS-1$
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
		GUIContext.getInstance().addContextListener(this);
	}

	@Override
	public void actionPerformed( final ActionEvent e )
	{
		final GUIContext context = GUIContext.getInstance();
		if ( !context.hasActiveSession() )
		{
			JOptionPane
					.showMessageDialog(
							MainWindow.getFrame(),
							MainWindow.getString("AccountOverviewAction.msg.nosession"), MainWindow.getString("AccountOverviewAction.titleError"), //$NON-NLS-1$ //$NON-NLS-2$
							JOptionPane.ERROR_MESSAGE);
			return;
		}
		final AccountListView view = new AccountListView();
		MainWindow.getDesktop().add(view);
		updateView(view);
	}

	public void updateView( final AccountListView view )
	{
		final GUIContext context = GUIContext.getInstance();
		final List<Session> sessions = context.getSessions();
		view.showIt(sessions.size() == 1 ? sessions.get(0).getCustomer() : null, AccountCache.getInstace().reloadAll(
				new Account[0]));
	}

	@Override
	public void contextEventPerformed( final int eventType )
	{
		setEnabled(GUIContext.getInstance().hasActiveSession());
	}

}
